// pages/databaseGuide/databaseGuide.js

const app = getApp()

Page({
  data: {
    openid: '',
    nickName: '',
    count: null,
    queryResult: '',
    selectData: [{ "id": 1, "name": "健康打卡" }],
    imgbox: [],//选择图片
    fileIDs: [],//上传云存储后的返回值
  },

  onLoad: function (options) {
    let that = this
    if (app.globalData.openid) {
      this.setData({
        openid: app.globalData.openid,
        nickName: app.globalData.nickName,
        avatarUrl: app.globalData.avatarUrl
      })
    }
    this.onQuery();
  },


  // 删除照片 &&
  imgDelete1: function (e) {
    let that = this;
    let index = e.currentTarget.dataset.deindex;
    let imgbox = this.data.imgbox;
    imgbox.splice(index, 1)
    that.setData({
      imgbox: imgbox
    });
  },
  // 选择图片 &&&
  addPic1: function (e) {
    var imgbox = this.data.imgbox;
    console.log(imgbox)
    var that = this;
   // var n = 5;
    //if (5 > imgbox.length > 0) {
   //   n = 5 - imgbox.length;
   // } else if (imgbox.length == 5) {
   //   n = 1;
   // }
    var n = 1;
    if (1 > imgbox.length > 0) {
      n = 1 - imgbox.length;
    } else if (imgbox.length == 1) {
      n = 1;
    }
    wx.chooseImage({
      count: n, // 默认9，设置图片张数
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // console.log(res.tempFilePaths)
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths

        if (imgbox.length == 0) {
          imgbox = tempFilePaths
        //} else if (5 > imgbox.length) {
        } else if (1 > imgbox.length) {
          imgbox = imgbox.concat(tempFilePaths);
        }
        that.setData({
          imgbox: imgbox
        });
      }
    })
  },

  checkboxChange: function (e) {
    console.log('checkbox发生change事件，携带value值为：', e.detail.value)
    console.log("长度:" + e.detail.value.length);
    app.globalData.status = e.detail.value
    this.setData({
      id: e.detail.value,
      length: e.detail.value.length
    })
  },

  //图片
  imgbox: function (e) {
    this.setData({
      imgbox: e.detail.value
    })
  },

  //发布按钮
  fb: function (e) {
    if (!this.data.imgbox.length) {
      wx.showToast({
        icon: 'none',
        title: '图片类容为空'
      });
    } else {
      //上传图片到云存储
      wx.showLoading({
        title: '上传中',
      })
      let promiseArr = [];
      for (let i = 0; i < this.data.imgbox.length; i++) {
        promiseArr.push(new Promise((reslove, reject) => {
          let item = this.data.imgbox[i];
          let suffix = /\.\w+$/.exec(item)[0];//正则表达式返回文件的扩展名
          wx.cloud.uploadFile({
            cloudPath: new Date().getTime() + suffix, // 上传至云端的路径
            filePath: item, // 小程序临时文件路径
            success: res => {
              this.setData({
                fileIDs: this.data.fileIDs.concat(res.fileID)
              });
              console.log(res.fileID)//输出上传后图片的返回地址
              app.globalData.headurl = res.fileID;
              reslove();
              wx.hideLoading();
              wx.showToast({
                title: "上传成功",
              })
            },
            fail: res => {
              wx.hideLoading();
              wx.showToast({
                title: "上传失败",
              })
            }
          })
        }));
      }
      Promise.all(promiseArr).then(res => {//等数组都做完后做then方法
        console.log("图片上传完成")
        this.setData({
          imgbox: []
        })
      })
    }
  },



  checkOrgExist: function (e) {
    const db = wx.cloud.database()
    //查询当前用户所有的 counters
    db.collection('ORGANIZATION').where({
      title: e.detail.value.title
    }).get({
      success: res => {
        console.log('[数据库] [查询记录] 成功: ', res)
        if(res.data.length > 0){
          wx.showToast({
            icon: 'none',
            title: '群组已存在'
          })
        }else{
          this.onAddPre(e)
        }
      },
      fail: err => {
        wx.showToast({
          icon: 'none',
          title: '校验群组是否存在失败'
        })
        console.error('[数据库] [查询记录] 失败：', err)
      }
    })
  },




  //图片
  addSec: function (e) {
    console.log("新建群组是否需要审核：" + e.detail.value.auth);
    var authflag;
    if (e.detail.value.auth){
      authflag = '0'
    }else{
      authflag = '1'
    }
    //第二步
    const db = wx.cloud.database()
    var content = e.detail.value.contentStr;

    var date = new Date();
    var Y = date.getFullYear() + '-';
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    var D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + '  ';
    var h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
    var m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
    var s = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());

    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var date = date.getDate();
    console.log("当前时间：" + Y + M + D + h + m + s);
    console.log("新增标题为：" + e.detail.value.title);
    console.log("新增日期为：" + e.detail.value.date);
    console.log("新增时间为：" + e.detail.value.time);
    console.log("新增地址为：" + e.detail.value.place);
    console.log("新增人数为：" + e.detail.value.count);
    console.log("新增活动详情为：" + e.detail.value.detail);
    console.log("新增活动图片路径为：" + app.globalData.headurl);

    var data = {
      content: e.detail.value.contentStr,
      name: app.globalData.nickName,
      status: app.globalData.status,
      addtime: Y + M + D + h + m + s,
      title: e.detail.value.title,
      date: e.detail.value.date,
      time: e.detail.value.time,
      detail: e.detail.value.detail,
      place: e.detail.value.place,
      orgstatus: '1',    //0待审核
      authflag: authflag,    //0待审核
      headurl: app.globalData.headurl
    }

    db.collection('ORGANIZATION').add({
      data: data,
      success: res => {
        app.globalData.headurl = null;        
        wx.hideLoading();

        var odata = {
          content: e.detail.value.contentStr,
          name: app.globalData.nickName,
          status: app.globalData.status,
          addtime: Y + M + D + h + m + s,
          title: e.detail.value.title,
          date: e.detail.value.date,
          time: e.detail.value.time,
          detail: e.detail.value.detail,
          place: e.detail.value.place,
          orgstatus: '1',    //0待审核
          authflag: authflag,    //0待审核
          headurl: app.globalData.headurl,
          _id: res._id
        }

        //新增管理员为群组成员
        var nickName = app.globalData.nickName;
        const db = wx.cloud.database()
        db.collection('USERORG').add({
          data: {
            nickName: nickName,
            avatarurl: app.globalData.avatarUrl,
            orgid: res._id,
            addtime: Y + M + D + h + m + s,
            applystatus: '1',
            orgdata: odata
          },
          success: res => {
            wx.reLaunch({
              url: '../msg/msg_success',
            })
            console.log('[数据库] [新增记录] 成功，记录 _id: ', res._id)
          },
          fail: err => {
            wx.reLaunch({
              url: '../msg/msg_fail',
            })
            console.error('[数据库] [新增记录] 失败：', err)
          }
        })
        //新增管理员结束
        console.log('[数据库] [新增记录] 成功，记录 _id: ', res._id)
      },
      fail: err => {
        app.globalData.headurl = null;
        wx.hideLoading();
        wx.reLaunch({
          url: '../msg/msg_fail',
        })
        console.error('[数据库] [新增记录] 失败：', err)
      }
    })
  },

  /**
   * 加入群组
   * */
  AppThisOrg: function (e) {
    var odata = e.currentTarget.dataset.id
    var nickName = app.globalData.nickName;
    const db = wx.cloud.database()
    db.collection('USERORG').add({
      data: {
        nickName: nickName,
        avatarurl: app.globalData.avatarUrl,
        orgid: odata._id,
        addtime: Y + M + D + h + m + s,
        applystatus: odata.authflag,
        orgdata: odata
      },
      success: res => {
        if (odata.authflag == '0') {
          wx.reLaunch({
            url: '../msg/msg_auth',
          })
        } else {
          wx.reLaunch({
            url: '../msg/msg_success',
          })
        }
        console.log('[数据库] [新增记录] 成功，记录 _id: ', res._id)
      },
      fail: err => {
        wx.reLaunch({
          url: '../msg/msg_fail',
        })
        console.error('[数据库] [新增记录] 失败：', err)
      }
    })
  },

  onAdd : function (e) {
    let that = this;
    if (!this.data.imgbox.length) {
      wx.showToast({
        icon: 'none',
        title: '请选择群组图片'
      });
    } 

    if (e.detail.value.title == "") {
      wx.showToast({
        icon: 'none',
        title: '请输入群组名称'
      })
      return false
    }

    if (e.detail.value.detail == "") {
      wx.showToast({
        icon: 'none',
        title: '请输入群组介绍'
      })
      return false
    }

    wx.cloud.init();
    wx.cloud.callFunction({
      name: 'msgSC',
      data: {
        text: e.detail.value.title + e.detail.value.detail
      }
    }).then((res) => {
      if (res.result.code == "200") {
        //检测通过,校验群组是否存在
        this.checkOrgExist(e)
      } else {
        //执行不通过
        wx.showToast({
          title: '包含敏感字哦。',
          icon: 'none',
          duration: 3000
        })
      }
    })
  },

  onAddPre: function (e) {
    let that = this;

    //第一步
    if (!this.data.imgbox.length) {
      wx.showToast({
        icon: 'none',
        title: '图片类容为空'
      });
    } else {
      //上传图片到云存储
      wx.showLoading({
        title: '正在处理中',
      })
      let promiseArr = [];
      for (let i = 0; i < this.data.imgbox.length; i++) {
        promiseArr.push(new Promise((reslove, reject) => {
          let item = this.data.imgbox[i];
          let suffix = /\.\w+$/.exec(item)[0];//正则表达式返回文件的扩展名
          wx.cloud.uploadFile({
            cloudPath: new Date().getTime() + suffix, // 上传至云端的路径
            filePath: item, // 小程序临时文件路径
            success: res => {
              this.setData({
                fileIDs: this.data.fileIDs.concat(res.fileID)
              });
              console.log(res.fileID)//输出上传后图片的返回地址
              app.globalData.headurl = res.fileID;
              reslove();

              //第二部，增加群组信息
              this.addSec(e);
            },
            fail: res => {
              wx.hideLoading();
              wx.showToast({
                title: "上传失败",
              })
              return;
            }
          })
        }));
      }
      
      Promise.all(promiseArr).then(res => {//等数组都做完后做then方法
        console.log("图片上传完成")
        this.setData({
          imgbox: []
        })
      })
    }
  },

  onPullDownRefresh: function () {
    this.onQuery()
  },


  bindDateChange: function (e) {
    this.setData({
      date: e.detail.value
    })
  },
  bindTimeChange: function (e) {
    this.setData({
      time: e.detail.value
    })
  },

  onQuery: function () {
    const db = wx.cloud.database()
    //查询当前用户所有的 counters
    db.collection('PVERSION').where({
        version: 2019
    }).orderBy('time', 'desc').get({
      success: res => {
        this.setData({
          queryResult: res.data
        })
        console.log('[数据库] [查询记录] 成功: ', res)
      },
      fail: err => {
        wx.showToast({
          icon: 'none',
          title: '查询记录失败'
        })
        console.error('[数据库] [查询记录] 失败：', err)
      }
    })
  },

  goHome: function() {
    const pages = getCurrentPages()
    if (pages.length === 2) {
      wx.navigateBack()
    } else if (pages.length === 1) {
      wx.redirectTo({
        url: '../index/index',
      })
    } else {
      wx.reLaunch({
        url: '../index/index',
      })
    }
  }
})